﻿using System;
using System.Linq;
using System.Data.Entity;
using System.Collections.Generic;
using System.Windows.Forms;
using PharmacyPharnet.Core;
using Pharmacy.Data.Entity;
using Pharmacy.ExceptionHandling;
using Pharmacy.Business;
using Pharmacy.Ultilities;
using Pharmacy.Data;
using Pharmacy.Data.Repositories;
using Pharmacy.Data.Core;
using Pharmacy.Business.Generator;
using Pharmacy.Ultilities.Resources;

namespace PharmacyPharnet.MasterData
{
    public partial class FrmManufacturer_Detail : FrmEditBase
    {
        #region Declarations
        Manufacturer currentObject = null;
        ManufacturerBO manufacturerBO;
        IObjectContext pharmacyContext;        
        #endregion

        #region Constructors
        public FrmManufacturer_Detail()
        {
            InitializeComponent();
        }

        public FrmManufacturer_Detail(Enums.ActionForm actionForm )
            :this()
        {
            CurrentAction = actionForm;
        }

        public FrmManufacturer_Detail(Manufacturer manufacturer, Enums.ActionForm actionForm, IObjectContext context)
            : this(actionForm)
        {
            currentObject = manufacturer;
            pharmacyContext = context;
        }
        #endregion

        #region Override Methods
        protected override void InitializeBO()
        {
            if (pharmacyContext == null)
                pharmacyContext = ObjectContextFactory.CreatePharmacyContext(Global.UserName, Global.CurrentConnectionString);
            if (manufacturerBO == null)
                manufacturerBO = new ManufacturerBO(pharmacyContext);

        }

        protected override void PopulateData()
        {
            BindDataToControls();
        }

        protected override void PopulateStaticData()
        {
            LoadManufacturerGroup(0);
            txtCodeEAN.Text = IdentityGeneratorHelper.GetNextNumber(Enums.GeneratorObjectType.ManufacturerGenerator, pharmacyContext.GetCurrentDateTime(), null, pharmacyContext);
        }
        #endregion

        #region Custom Methods
        private void LoadManufacturerGroup(int selectedID)
        {
            ManufacturerGroupRepository rManufacturerGroup = new ManufacturerGroupRepository(pharmacyContext, MergeOption.Overrive);
            List<ManufacturerGroup> lstManufacturerGroup= rManufacturerGroup.AsQueryable().ToList();
            lueManufacturerGroup.Properties.DataSource = lstManufacturerGroup;
            lueManufacturerGroup.Properties.DropDownRows = lstManufacturerGroup.Count;
            if (selectedID > 0)
                lueManufacturerGroup.EditValue = selectedID;
        }

        private void RegisterEventhandler()
        {
            btnNew.Click += new EventHandler(btnNew_Click);
            btnCancel.Click += new EventHandler(btnCancel_Click);
            btnDelete.Click += new EventHandler(btnDelete_Click);
            btnSave.Click += new EventHandler(btnSave_Click);
        }

        private void ClearData()
        {
            txtCodeEAN.Text = IdentityGeneratorHelper.GetNextNumber(Enums.GeneratorObjectType.ManufacturerGenerator, pharmacyContext.GetCurrentDateTime(), null, pharmacyContext);
            txtContactInfoName.Text = string.Empty;
            txtContactMobilePhone.Text = string.Empty;
            txtContactPhone.Text = string.Empty;
            txtFax.Text = string.Empty;
            txtFullName.Text = string.Empty;
            txtName.Text = string.Empty;
            txtNote.Text = string.Empty;
            txtNumber.Text = string.Empty;
            txtPhone.Text = string.Empty;
            txtShippingInfoAddress.Text = string.Empty;
            txtTaxNumber.Text = string.Empty;
            txtWebsite.Text = string.Empty;
            lueManufacturerGroup.EditValue = null;
            CurrentAction = Pharmacy.Ultilities.Enums.ActionForm.New;
        }

        private void BindDataToControls()
        {
            if (currentObject != null && CurrentAction == Pharmacy.Ultilities.Enums.ActionForm.Edit)
            {
                txtCodeEAN.Text = currentObject.CodeEAN;
                txtFullName.Text = currentObject.FullName;
                txtName.Text = currentObject.Name;
                txtNote.Text = currentObject.Note;
                txtNumber.Text = currentObject.ManufacturerNumber;
                lueManufacturerGroup.EditValue = currentObject.ManufacturerGroup.ID;
                if (currentObject.ContactInfo != null)
                {
                    ContactInfo contactInfo = currentObject.ContactInfo;
                    txtContactInfoName.Text = contactInfo.Name;
                    txtContactMobilePhone.Text = contactInfo.MobilePhone;
                    txtContactPhone.Text = contactInfo.Phone;
                }
                if (currentObject.ShippingInfo != null)
                {
                    ShippingInfo shippingInfo = currentObject.ShippingInfo;
                    txtFax.Text = shippingInfo.Fax;
                    txtPhone.Text = shippingInfo.Phone;
                    txtShippingInfoAddress.Text = shippingInfo.Address;
                    txtTaxNumber.Text = shippingInfo.TaxNumber;
                    txtWebsite.Text = shippingInfo.Website;
                }
                CurrentAction = Pharmacy.Ultilities.Enums.ActionForm.Edit;
            }
        }

        private void BindDataToObject()
        {
            if (currentObject == null || CurrentAction == Enums.ActionForm.New )
            {
                currentObject = null;
                currentObject = new Manufacturer();
            }
            currentObject.CodeEAN = txtCodeEAN.Text.Trim();
            currentObject.FullName = txtFullName.Text.Trim();
            currentObject.Name = txtName.Text.Trim();
            currentObject.Note = txtNote.Text.Trim();
            currentObject.ManufacturerNumber = txtNumber.Text.Trim();
            currentObject.ManufacturerGroup = lueManufacturerGroup.Properties.GetDataSourceRowByKeyValue(lueManufacturerGroup.EditValue) as ManufacturerGroup;
            #region Contact Info
            if (txtContactInfoName.Text.Trim().Length > 0
                ||txtContactMobilePhone.Text.Trim().Length > 0
                || txtContactPhone.Text.Trim().Length > 0)
            {
                ContactInfo contactInfo = new ContactInfo() 
                                            { Name = txtContactInfoName.Text.Trim(), 
                                                MobilePhone = txtContactMobilePhone.Text.Trim(), 
                                                Phone = txtContactPhone.Text.Trim() };
                currentObject.ContactInfo = contactInfo;
            }
            #endregion            
            #region Shipping Info
            if (txtShippingInfoAddress.Text.Trim().Length > 0
                ||txtFax.Text.Trim().Length > 0
                || txtPhone.Text.Trim().Length > 0
                || txtTaxNumber.Text.Trim().Length > 0
                || txtWebsite.Text.Trim().Length > 0)
            {
                ShippingInfo shippingInfo = new ShippingInfo() 
                                            { 
                                                Fax = txtFax.Text.Trim(),
                                                Phone = txtPhone.Text.Trim(),
                                                Address = txtShippingInfoAddress.Text.Trim(),
                                                TaxNumber = Text.Trim(),
                                                Website = txtWebsite.Text.Trim()
                                            };
                currentObject.ShippingInfo = shippingInfo;
            }
            #endregion            
        }

        private bool Validate()
        {
            bool isValid = true;
            if(txtNumber.Text.Trim().Length <= 0)
            {
                txtNumber.ErrorText = string.Format(SR.Instance.GetString(Constant.KEY_EMPTYINFORMATION), Constant.ENT_MANUFACTURERNUMBER);
                isValid = false;
            }
            if (txtName.Text.Trim().Length <= 0)
            {
                txtName.ErrorText = string.Format(SR.Instance.GetString(Constant.KEY_EMPTYINFORMATION), Constant.ENT_MANUFACTURERNAME);
                isValid = false;
            }
            if (lueManufacturerGroup.EditValue == null || lueManufacturerGroup.Text.Trim().Length <= 0)
            {
                lueManufacturerGroup.ErrorText = string.Format(SR.Instance.GetString(Constant.KEY_EMPTYINFORMATION), Constant.ENT_MANUFACTURERGROUP);
                isValid = false;
            }
            //Reload Manufacturer
            else if (lueManufacturerGroup.EditValue != null)
            {
                ManufacturerGroupRepository rManufacturerGroup = new ManufacturerGroupRepository(pharmacyContext);
                int selectedManufacturerID = (lueManufacturerGroup.Properties.GetDataSourceRowByKeyValue(lueManufacturerGroup.EditValue) as ManufacturerGroup).ID;
                ManufacturerGroup objTemp = rManufacturerGroup.AsQueryable().Where(m => m.ID == selectedManufacturerID).First();
                if (objTemp == null)
                {
                    lueManufacturerGroup.ErrorText = string.Format(SR.Instance.GetString(Constant.KEY_OBJECTISDELETED), Constant.ENT_MANUFACTURERGROUP);
                    isValid = false;
                }
            }            
            return isValid;
        }
        #endregion

        #region Event Handlers
        private void FrmManufacturer_Detail_Load(object sender, EventArgs e)
        {
            try
            {
                RegisterEventhandler();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Vui lòng liên hệ Người quản trị hệ thống để được hỗ trợ.");
                ExceptionHandler.LogWriter.Write(ex, ExceptionHandler.LOG_CAT_GENERAL);
                this.Close();
            }
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                bool result = true;
                string message = string.Empty;
                if (Validate())
                {
                    ViewManager.CreateWaitDialog();
                    ViewManager.SetWaitDialogCaption(SR.Instance.GetString(Constant.ENT_MANUFACTURER), "Saving...");
                    string errorMessage = string.Empty;
                    BindDataToObject();
                    if (CurrentAction == Enums.ActionForm.New)
                    {
                        manufacturerBO.CreateNewManufacturer(currentObject);
                        ClearData();
                    }
                    if (CurrentAction == Enums.ActionForm.Edit)
                    {
                        result = manufacturerBO.EditManufacturer(currentObject, out message);
                        if (result == false)
                        {
                            MessageBox.Show(message);
                            return;
                        }
                    }
                }

            }
            catch (PessimisticLockingException ex)
            {
                MessageBox.Show(ex.Message);
                ExceptionHandler.LogWriter.Write(ex, ExceptionHandler.LOG_CAT_GENERAL);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Vui lòng liên hệ Người quản trị hệ thống để được hỗ trợ.");
                ExceptionHandler.LogWriter.Write(ex, ExceptionHandler.LOG_CAT_GENERAL);
                this.Close();
            }
            finally {
                ViewManager.CloseWaitDialog();
            }
        }

        void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                bool result = true;
                string message = string.Empty;
                if (currentObject != null && CurrentAction == Enums.ActionForm.Edit)
                {
                    ViewManager.CreateWaitDialog();
                    ViewManager.SetWaitDialogCaption(SR.Instance.GetString(Constant.ENT_MANUFACTURER), "Deleting...");
                    result = manufacturerBO.DeleteManufacturer(currentObject.ID, out message);
                    if (result == false)
                    {
                        MessageBox.Show(message);
                        return;
                    }
                    ClearData();
                }
            }
            catch (PessimisticLockingException ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Vui lòng liên hệ Người quản trị hệ thống để được hỗ trợ.");
                ExceptionHandler.LogWriter.Write(ex, ExceptionHandler.LOG_CAT_GENERAL);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Vui lòng liên hệ Người quản trị hệ thống để được hỗ trợ.");
                ExceptionHandler.LogWriter.Write(ex, ExceptionHandler.LOG_CAT_GENERAL);
                this.Close();
            }
            finally {
                ViewManager.CloseWaitDialog();
            }
        }

        void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                if (CurrentAction == Pharmacy.Ultilities.Enums.ActionForm.New)
                    ClearData();
                if (CurrentAction == Pharmacy.Ultilities.Enums.ActionForm.Edit)
                    BindDataToControls();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Vui lòng liên hệ Người quản trị hệ thống để được hỗ trợ.");
                ExceptionHandler.LogWriter.Write(ex, ExceptionHandler.LOG_CAT_GENERAL);
                this.Close();
            }
        }

        void btnNew_Click(object sender, EventArgs e)
        {
            try
            {
                ClearData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Vui lòng liên hệ Người quản trị hệ thống để được hỗ trợ.");
                ExceptionHandler.LogWriter.Write(ex, ExceptionHandler.LOG_CAT_GENERAL);
                this.Close();
            }
        }

        private void lueManufacturerGroup_ButtonPressed(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Ellipsis)
                {
                    FrmListManufacturerGroup frmManufacturerGroup = new FrmListManufacturerGroup();
                    frmManufacturerGroup.ucMasterData.RowSelected += frmManufacturerGroup_RowSelected;
                    frmManufacturerGroup.Show();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Vui lòng liên hệ Người quản trị hệ thống để được hỗ trợ.");
                ExceptionHandler.LogWriter.Write(ex, ExceptionHandler.LOG_CAT_GENERAL);
                this.Close();
            }
        }

        void frmManufacturerGroup_RowSelected(object sender, Pharmacy.Ultilities.BaseEventArgs.RowSelectedArgs e)
        {
            try
            {
                int id = e.CurrentSelectedRowID;
                if (id > 0)
                {
                    LoadManufacturerGroup(id);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Vui lòng liên hệ Người quản trị hệ thống để được hỗ trợ.");
                ExceptionHandler.LogWriter.Write(ex, ExceptionHandler.LOG_CAT_GENERAL);
                this.Close();
            }
        }
        #endregion        
    }
}